package com.sky.com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.BusinessException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    @Autowired
    SetmealMapper setmealMapper;

    // 分页
    @Override
    public PageResult getPage(DishPageDTO dishPageDTO) {
        //1. 开启分页
        PageHelper.startPage(dishPageDTO.getPage(),dishPageDTO.getPageSize());
        //2. 查询list
        List<DishVO> voList = dishMapper.getList(dishPageDTO);
        Page<DishVO> page = (Page<DishVO>) voList;
        //3. 返回分页
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO
     **/
    @Transactional
    @Override
    public void saveDishWithFlavor(DishDTO dishDTO) {
      //1. 参数校验
        // 2. 业务校验
        Dish oldDish = dishMapper.getByNmae(dishDTO.getName());
        if(oldDish != null){
            throw new BusinessException(200,"菜品已存在");
        }
        //3. 菜品dto->菜品entity
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        //4.补充状态
        dish.setStatus(StatusConstant.DISABLE);//禁用
        //5. 调用dishMapper新增(主键返回)
        log.info("菜品新增前id:{}",dish.getId());
        dishMapper.insert(dish);
        log.info("菜品新增后id: {}",dish.getId());
        //6.取出口味列表
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        //7.遍历
        if(ArrayUtil.isNotEmpty(flavorList)){
            for (DishFlavor dishFlavor : flavorList) {
                //管理菜品id
                dishFlavor.setDishId(dish.getId());
                //保存口味
                dishFlavorMapper.insert(dishFlavor);
            }
        }

    }


    // 回显菜品
    @Override
    public DishVO getById(Long id) {
      //1. 先查菜品
        Dish dish = dishMapper.getById(id);
        //2. 再根据菜品id查询口味列表
        List<DishFlavor> flavorList = dishFlavorMapper.getListByDishId(id);
        //3. 封装vo
        DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
        dishVO.setFlavors(flavorList);
        //4.返回vo
        return dishVO;
    }

    @Override
    public Dish getById2(Long id) {
        return dishMapper.getById(id);
    }

    // 修改菜品
    @Override
    @Transactional
    public void updateById(DishDTO dishDTO) {
       //1. 先修改菜品基本信息
        // 1-1 dto转实体
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        // 1-2 调用mapper修改
        dishMapper.updateById(dish);
        //2. 删除此慈阿庞口味列表
        dishFlavorMapper.deleteByDishId(dish.getId());
        //3.遍历新口味
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if(ArrayUtil.isNotEmpty(flavorList)){
            for (DishFlavor dishFlavor : flavorList) {
                //3-1 关联菜品id
                dishFlavor.setDishId(dish.getId());
                //3-2 保存菜品
                dishFlavorMapper.insert(dishFlavor);
            }

        }
    }

    /**
     * 菜品批量删除
     *
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(Long[] ids) {
        //1. 参数检验
        if (ids == null || ids.length < 1) {
            return;
        }
        //2.业务检验
        //2.1 根据ids统计起售中的菜品数量
        Integer count = dishMapper.countByIdsAndStatus(ids, StatusConstant.ENABLE);
        if (count != null && count > 0) {
            throw new BusinessException(500, "选项中有启售状态的菜品，不能删除");
        }
        for (Long dishId : ids) {
            //2.2根据ids查询是否关联套餐
            List<SetmealDish> setmealList = setmealDishMapper.listByDishId(dishId);
            if (setmealList != null && setmealList.size() > 0) {
                Dish dish = dishMapper.getById(dishId);
                throw new BusinessException(500, "菜品【" + dish.getName() + "】关联了套餐,不能删除");
            }
            //3. 实现业务-批量删除
            //3.1 删除菜品后，关联的口味数据也需要删除掉
            dishMapper.deleteById(dishId);
            dishFlavorMapper.deleteByDishId(dishId);
        }

    }


    // 启用禁用
    @Override
    @Transactional
    public void startOrStop(Integer status, Long id) {
       //1. 封装实体
        Dish dish = Dish.builder().id(id).status(status).build();
        //2. 修改菜品状态
        dishMapper.updateById(dish);
        //3. 判断是否为禁用
        if(status.equals(StatusConstant.DISABLE)){
            //同时禁用关联的套餐
            setmealMapper.updateStatusByDishId(status,id);
        }

    }

    // 查询菜品列表
    @Override
    public List<DishVO> getList(DishPageDTO dishPageDTO) {
        return dishMapper.getList(dishPageDTO);
    }

    // 条件查询
    @Override
    public List<DishVO> getParamList(DishPageDTO dishPageDTO) {
       //1. 先查询菜品列表
        List<DishVO> voList = dishMapper.getList(dishPageDTO);

        //2. 遍历菜品
        voList.forEach(dishVO -> {
            //根据菜品id查询口味
            List<DishFlavor> flavorList = dishFlavorMapper.getListByDishId(dishVO.getId());
            //将口味封装到vo
            dishVO.setFlavors(flavorList);
        });
        //3.返回
        return voList;
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageDTO
     * @return
     **/
    @Override
    public PageResult page(DishPageDTO dishPageDTO) {
        //1.开启分页
        PageHelper.startPage(dishPageDTO.getPage(), dishPageDTO.getPageSize());
        //2. 查询
        List<DishVO> list = dishMapper.list(dishPageDTO);
        PageInfo<DishVO> pageInfo = new PageInfo<>(list);
        //3. 封装分页对象
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 根据id查询菜品和对应的口味数据
     *
     * @param dishId
     * @return
     **/
    @Override
    public DishVO getByIdWithFlavor(Long dishId) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(dishId);

        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.listByDishId(dishId);

        //将擦汗寻到的数据封装到VO
        DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改菜品基本信息和对应口味信息
     *
     * @param dishDTO
     **/
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //拷贝菜品相关数据
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        //修改菜品表基本信息
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }

    }



    /**
     * 菜品起售停售
     * @param status
     * @param dishId
     * **/
    @Override
    public void enableOrDisable(Integer status, Long dishId) {
        //停售 需要停售对应的套餐
        Dish dish = Dish.builder()
                .id(dishId)
                .status(status)
                .build();
        //2. 修改参评状态
        dishMapper.update(dish);
        //3.修改菜品关联套餐状态
        if(status == 0){
            setmealMapper.updateStatusByDishId(status,dishId);
        }
    }


    /**
     * 根据分类ID查询菜品列表
     * @param dishDTO
     * @return
     * **/
    @Override
    public List<Dish> listByCid(DishDTO dishDTO) {
        if(dishDTO.getCategoryId() == null){
            throw new BusinessException(500,"分类ID不能为空");
        }
        //条件查询
        return dishMapper.paramList(dishDTO);
    }

    /**
     * 根据分类ID查询菜品列表，包含口味
     * @param dishDTO
     * @return
     * **/
    @Override
    public List<DishVO> listWithFlavor(DishDTO dishDTO) {
        //根据分类id查询菜品列表
        List<Dish> dishes = dishMapper.paramList(dishDTO);
        //准备集合，存放DishVO
        ArrayList<DishVO> dishVOS = new ArrayList<>();
        dishes.forEach(dish -> {
            //查村菜品及关联口味
            List<DishFlavor> flavors = dishFlavorMapper.listByDishId(dish.getId());
            DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
            //添加到集合中
            dishVOS.add(dishVO);
        });
        return dishVOS;
    }

    @Override
    public List<Dish> listByIds(Long[] ids) {
        return dishMapper.getByIds(ids);
    }
}




